<template>
  <div class="home-container">
    <el-container>
      <el-header>
        <div class="left"></div>
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          style="margin: 0 auto"
        >
          <el-menu-item index="1" @click="navigateTo('/home')">
            商店主页
          </el-menu-item>
          <el-menu-item index="2">购物车</el-menu-item>
        </el-menu>
        <div class="line">
          <el-link @click="navigateTo('/order')" target="_blank">
            我的订单
          </el-link>
          &emsp;|&emsp;
          <el-link @click="deleteUser()" target="_blank">注销账户</el-link>
        </div>
      </el-header>

      <el-main>
        <!-- 购物车表格 -->
        <div class="CartBox">
          <el-table
            ref="multipleTable"
            :data="CartData"
            tooltip-effect="dark"
            style="width: 100%; font-size: 20px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="80"></el-table-column>
            <el-table-column label="商品图片" width="200">
              <template #default="scope">
                <img
                  :src="scope.row.image"
                  alt="SmallImage"
                  class="resized-image"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="商品名称"
              width="400"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="price"
              label="单价"
              width="140"
            ></el-table-column>
            <el-table-column label="数量" width="200">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.quantity"
                  @change="quantityChange(scope.row)"
                  :min="1"
                  :max="10"
                  size="small"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="小计" width="180">
              <template #default="scope">
                <div class="TotalPrice">
                  {{ scope.row.price * scope.row.quantity }}元
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteCart(scope.row.id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
      <!-- 底边 -->
      <el-footer>
        <div class="FooterBox">
          <div class="chose-quantity">
            你已经选择了{{ multipleSelection.length }}件商品
          </div>
          <div class="total-price">
            合计：{{ totalprice }}元
            <el-button
              :disabled="multipleSelection.length === 0"
              class="btn-primary"
              @click="buy"
            >
              去结算
            </el-button>
          </div>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  name: 'ProductCart',
  data() {
    return {
      activeIndex: '2', // 默认激活的菜单项
      CartData: [],
      multipleSelection: [], // 存储选中的行
    }
  },
  computed: {
    totalprice() {
      return this.multipleSelection.reduce((sum, item) => {
        return sum + item.price * item.quantity
      }, 0)
    },
  },
  mounted() {
    this.getCartData()
  },
  methods: {
    //导航栏跳转
    navigateTo(path) {
      this.$router.push(path)
    },
    //获取购物车列表
    getCartData() {
      const token = localStorage.getItem('jwtToken') // 获取存储的 token

      this.$http
        .get('/api/cart/list', {
          headers: {
            Authorization: `Bearer ${token}`, // 使用 Bearer 方案
          },
        })
        .then((res) => {
          this.CartData = res.data.data
          console.log(this.productData.data)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //选择框
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row) //切换该行的选择状态
        })
      } else {
        this.$refs.multipleTable.clearSelection() //清空表格中所有行的选中状态
      }
    },
    handleSelectionChange(val) {
      console.log('Selected rows:', val) // 输出选中行的内容
      this.multipleSelection = val // 保存当前选中行
    },
    //删除购物车商品
    async deleteCart(id) {
      try {
        const token = localStorage.getItem('jwtToken') // 获取存储的 token
        const response = await this.$http.delete('/api/cart/' + id, {
          headers: { Authorization: `Bearer ${token}` },
        })
        if (response.data.code === 1) {
          this.multipleSelection = [] // 清空选中的商品
          this.getCartData() // 重新获取购物车数据，刷新页面
        }
      } catch (error) {
        console.error('删除失败', error)
      }
    },
    //更改商品数量
    async quantityChange(value) {
      console.log('更改商品数量')
      console.log(value)
      try {
        const token = localStorage.getItem('jwtToken') // 获取存储的 token
        const cartItems = [
          {
            id: value.id,
            quantity: value.quantity,
            status: 0,
          },
        ]
        console.log('cartItems:', cartItems) // 输出选中行的内容
        const response = await this.$http.post(
          '/api/cart/modify',
          cartItems, // 直接发送数组格式的 cartItems
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        )
        if (response.data.code === 1) {
          this.multipleSelection = [] // 清空选中的商品
          this.getCartData() // 重新获取购物车数据，刷新页面
        }
      } catch (error) {
        console.error('购买失败', error)
      }
    },
    //注销用户
    deleteUser() {
      const token = localStorage.getItem('jwtToken') // 获取存储的 token
      this.$confirm('此操作将永久注销该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http.delete('/api/user', {
            headers: { Authorization: `Bearer ${token}` },
          })
          this.$message({
            type: 'success',
            message: '注销成功!',
          })
          // 删除成功，清除 localStorage 中的 jwtToken
          localStorage.removeItem('jwtToken')
          // 跳转到登录页面
          this.$router.push('/login')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //去结算
    async buy() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要购买的商品')
      } else {
        // 执行购买操作
        try {
          const token = localStorage.getItem('jwtToken') // 获取存储的 token
          const cartItems = this.multipleSelection.map((item) => ({
            id: item.id,
            quantity: item.quantity,
            productId: item.productId,
            status: 1,
          }))
          console.log('cartItems:', cartItems) // 输出选中行的内容
          const response = await this.$http.post(
            '/api/cart/modify',
            cartItems, // 直接发送数组格式的 cartItems
            {
              headers: { Authorization: `Bearer ${token}` },
            }
          )
          if (response.data.code === 1) {
            alert('成功购买商品！')
            this.multipleSelection = [] // 清空选中的商品
            this.getCartData() // 重新获取购物车数据，刷新页面
          }
        } catch (error) {
          console.error('购买失败', error)
        }
      }
    },
  },
}
</script>

<style scoped>
.home-container {
  margin: 20px;
}

.el-header {
  display: flex;
  justify-content: space-between;
}
.left {
  width: 120px;
}
.line {
  width: 150px;
  display: flex;
  align-items: center;
}
.el-footer {
  background-color: #bfc7d2;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.order-box {
  margin: 0 0 0 0;
  padding: 0px;
}
.el-link {
  margin: 0 0px 0 0;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
}
.CartBox {
  margin: 0 134px 0;
  padding: 0px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.resized-image {
  max-width: 120px;
  max-height: 120px;
  object-fit: contain;
}
.TotalPrice {
  font-size: 20px;
  line-height: 1;
  color: #ff6700;
  padding: 12px 0 10px;
}

.FooterBox {
  display: flex; /* 使用flex布局 */
  justify-content: space-between; /* 让元素分布在两端 */
  align-items: center; /* 垂直居中对齐 */
  margin: 0 134px 0;
  background-color: #b3c0d1;
}
.chose-quantity {
  padding: 0 0px 0px 20px; /* 上右下左 */
  text-align: left;
  width: 200px;
}
.total-price {
  color: #ff6700;
  font-size: 24px;
}
.btn-primary {
  max-height: 60px;
  padding: 15px 40px;
  font-size: 24px;
  margin-left: 20px;
  background: #ff6700;
  border-color: #ff6700;
  color: #fff;
}
</style>
